package com.zb.zeus.common.redis.configure;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.io.ByteArrayOutputStream;
import java.util.Objects;

/**
 * @author fujianjian
 * @since 2021/4/6 17:07
 */
@Slf4j
public class KyroRedisSerializer<T> implements RedisSerializer<T> {
    public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];

    private Kryo kryo;
    private Class<T> clazz;

    //private static final ThreadLocal<Kryo> kryos = ThreadLocal.withInitial(Kryo::new);

    public KyroRedisSerializer(Class<T> clazz) {
        this.clazz = clazz;
        kryo = new Kryo();
        kryo.setReferences(true);
        kryo.setRegistrationRequired(false);
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (Objects.isNull(t)) {
            return EMPTY_BYTE_ARRAY;
        }
        //Kryo kryo = kryoPool.borrow();
        //kryo.reference(false);
        //kryo.register(clazz);
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             Output output = new Output(baos)) {
            kryo.writeClassAndObject(output, t);
            output.flush();
            return baos.toByteArray();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return EMPTY_BYTE_ARRAY;
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }

        //Kryo kryo = kryoPool.borrow();
        kryo.setReferences(false);
        //kryo.register(clazz);

        try (Input input = new Input(bytes)) {
            return (T) kryo.readClassAndObject(input);
        } catch (Exception e) {
            log.error("deserialize occur error", e);
            return null;
        }
    }
}
